from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.ocr.v20181119 import ocr_client, models
from common.config import cfg

def init_ocr_client():
    """初始化腾讯云OCR客户端"""
    # 实例化一个认证对象
    cred = credential.Credential(cfg['tencent']['SecretId'], cfg['tencent']['SecretKey'])
    
    # 实例化一个http选项，可选的，没有特殊需求可以跳过
    httpProfile = HttpProfile()
    httpProfile.endpoint = "ocr.tencentcloudapi.com"

    # 实例化一个client选项，可选的，没有特殊需求可以跳过
    clientProfile = ClientProfile()
    clientProfile.httpProfile = httpProfile
    
    # 实例化要请求产品的client对象
    return ocr_client.OcrClient(cred, "ap-guangzhou", clientProfile)

def recognize_id_card(image_base64: str, card_side: str = "FRONT"):
    """识别身份证信息
    
    Args:
        image_base64: base64编码的图片数据
        card_side: 身份证方向，FRONT为正面，BACK为反面
        
    Returns:
        dict: 识别结果
    """
    try:
        # 实例化OCR客户端
        client = init_ocr_client()
        
        # 实例化一个请求对象，根据调用的接口和实际情况，可以进一步设置请求参数
        req = models.IDCardOCRRequest()
        
        # 设置图片数据和身份证方向
        req.ImageBase64 = image_base64
        req.CardSide = card_side
        
        # 返回的resp是一个IDCardOCRResponse的实例，与请求对象对应
        response = client.IDCardOCR(req)
        
        # 输出json格式的字符串回包
        return response.to_json_string()
        
    except Exception as e:
        # 处理异常情况
        return {"error": str(e)}